# Created by Daniel Vaughan 2011

function ReplaceText($fileInfo, $matchPattern)
{
    if( $fileInfo.GetType().Name -ne 'FileInfo')
    {
        # Reject DirectoryInfo and other types
         return
    }

    $regex = new-object System.Text.RegularExpressions.Regex ($matchPattern, [System.Text.RegularExpressions.RegexOptions]::MultiLine)
    $content = (Get-Content $fileInfo.FullName)
 
    $sb = new-object System.Text.StringBuilder
    [bool] $skipNext = $false
    [bool] $replacedText = $false
    
    Foreach($line in $content)
    {
        $matchResult = $regex.Match($line)
        if ($matchResult.Success)
        {
            $replacementText = $matchResult.Groups["r"].Value.Replace('&quot;', '"')
            [void]$sb.AppendLine($replacementText)
            $skipNext = $true
            $replacedText = $true
        }
        else
        {
            if ($skipNext)
            {
                $skipNext = $false
            }
            else
            {
                [void]$sb.AppendLine($line)
            }
        }           
    } 

    $result = $sb.ToString()
    #Write-Host $result
    
    if ($replacedText)
    {
        Set-Content $fileInfo.FullName $result
        Write-Host "Replaced text in file: " $fileInfo.FullName
    }
}

# App Template
$executingScriptDirectory = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent
$sourceDirectory = $executingScriptDirectory + '\AppTemplate.WinRT.CSharp.VS12\'
$itemsDirectory = $executingScriptDirectory + '\ItemTemplates.WinRT.CSharp.VS12\'
$tempDirectory = $executingScriptDirectory + '\TempZip\'
$targetDirectory = $executingScriptDirectory + '\VSTemplates\Packages\'
# Visual Studio template zip files (the final result)
echo $executingScriptDirectory
$vsTemplatesDirectory = $executingScriptDirectory + '\VSTemplates\'

#zipping
$zipLibraryPath = $executingScriptDirectory + '\ICSharpCode.SharpZipLib.dll'
#[System.IO.Path]::GetFullPath([System.IO.Path]::Combine($executingScriptDirectory.ToString(), 
#  "\\ICSharpCode.SharpZipLib.dll"));
#  "..\\..\\..\\..\\Libraries\\SharpZipLib\\ICSharpCode.SharpZipLib.dll"));

[void][Reflection.Assembly]::LoadFile($zipLibraryPath);
$zip = new-object ICSharpCode.SharpZipLib.Zip.FastZip;
$zip.CreateEmptyDirectories = $true;


if (Test-Path $tempDirectory)
{
    get-childitem $tempDirectory -recurse | remove-item -recurse -force
    Remove-Item -Recurse -Force $tempDirectory
}

###################
# App Template

Write-Host 'Processing App Template'

Copy-Item $sourceDirectory $tempDirectory -recurse

# The command Copy-Item -exclude doesn't work properly, so manually delete stuff.
$deleteDirs = @('Bin', 'obj')
foreach ($deleteDir in $deleteDirs)
{
    $fullDir = $tempDirectory + $deleteDir
    if (Test-Path $fullDir)
    {
        get-childitem $fullDir -recurse | remove-item -recurse -force
        Remove-Item -Recurse -Force $fullDir
    }
}

$tempFiles = Get-ChildItem $tempDirectory -recurse -force

ForEach ($tempFile in $tempFiles) 
{ 
    if ($tempFile.Attributes -ne "Directory") 
    { 
        $tempFile.IsReadOnly = $false 
    } 
}

attrib C:\CodePlex\Calcium\Trunk\Source\Calcium\WinRT\Installation\TempZip\PageView.xaml.cs -r

Write-Host 'Replacing tags'

$matchPattern = '(/\* d:TR (?<r>.*) \*/)'#'(/\* d:TR (?<r>.*) \*/.*\n.*$)'
#$replacementPattern = '${r}'
$csFiles = Get-ChildItem -include *.cs -recurse $tempDirectory
#$csFiles | % { ReplaceText $_ $matchPattern }

$ttFiles = Get-ChildItem -include *.tt -recurse $tempDirectory
#$ttFiles | % { ReplaceText $_ $matchPattern }

$matchPattern = 'd:TR="(?<r>.*)"'
$xamlFiles = Get-ChildItem -include *.xaml -recurse $tempDirectory
#$xamlFiles | % { ReplaceText $_ $matchPattern }
$matchPattern = 'd:TR2="(?<r>.*)"'
# Have to retrieve files again otherwise changes are not retained.
$xamlFiles = Get-ChildItem -include *.xaml -recurse $tempDirectory
#$xamlFiles | % { ReplaceText $_ $matchPattern }

$matchPattern = '<!-- d:TR (?<r>.*) -->'
$xmlFiles = Get-ChildItem -include *.xml -recurse $tempDirectory
#$xmlFiles | % { ReplaceText $_ $matchPattern }

$csprojFiles = Get-ChildItem -include *.csproj -recurse $tempDirectory
$csprojFiles | % { ReplaceText $_ $matchPattern }

$includeFiles = @('*.cs', '*.xaml', '*.xml', '*.csproj', '*.tt')
$allFiles = Get-ChildItem -include $includeFiles -recurse $tempDirectory | Where-Object {$_.PSIsContainer -eq $false}
foreach ($file in $allFiles) 
{ 
    ((Get-Content $file.FullName) -replace 'CalciumTemplateApp','$safeprojectname$') | 
                set-content $file.FullName -Force
} 

Write-Host 'Replacing guid in Package.appxmanifest'
$manifestPath = $tempDirectory + 'Package.appxmanifest'
((Get-Content $manifestPath) -replace '818d17c2-37ab-44da-a79d-04aba2503b4a', '$guid1$') | 
        set-content $manifestPath

Write-Host 'Coping .vstemplate file'
Copy-Item -force ($vsTemplatesDirectory + 'App.WinRT.CSharp.VS12.vstemplate') $tempDirectory

$appZip = $targetDirectory + "CalciumWinRTApp_VS12_CS.zip"
Write-Host 'Outputting zip file to ' $appZip
$zip.CreateZip($appZip, $tempDirectory, $true, "")
        # Give the zip operation some time to complete.
        #[System.Threading.Thread]::Sleep(2000)

if (Test-Path $tempDirectory)
{
    Write-Host 'Deleting temp directory'
    get-childitem $tempDirectory -recurse | remove-item -recurse -force
    Remove-Item -Recurse -Force $tempDirectory
}

Write-Host 'Finished process App Template'

###################
# View Template

Write-Host 'Processing View Template'

New-Item $tempDirectory -type directory | Out-Null

$viewItems = 'PageView.xaml', 'PageView.xaml.cs', 'PageViewModel.cs'
foreach ($item in $viewItems)
{ 
    Copy-Item ($itemsDirectory + $item) $tempDirectory -force
    $target = $tempDirectory + $item
    (Get-Item $target).IsReadOnly = $false
    ((Get-Content $target) -replace 'CalciumTemplateApp','$rootnamespace$') | 
        set-content $target        
}

Write-Host 'Replacing tags'

# Replace d:TR tags in files.
$csFiles = Get-ChildItem -include *.cs -recurse $tempDirectory
$csFiles | % { ReplaceText $_ '(/\* d:TR (?<r>.*) \*/)' }

$xamlFiles = Get-ChildItem -include *.xaml -recurse $tempDirectory
$xamlFiles | % { ReplaceText $_ 'd:TR="(?<r>.*)"' }
$xamlFiles = Get-ChildItem -include *.xaml -recurse $tempDirectory
$xamlFiles | % { ReplaceText $_ 'd:TR2="(?<r>.*)"' }

# Copy the icon file from the app project
Copy-Item ($sourceDirectory + 'TemplateIcon.ico') $tempDirectory -force 

# Copy the vstemplate file
Copy-Item -force ($vsTemplatesDirectory + 'View.WinRT.CSharp.VS12.vstemplate') $tempDirectory

Write-Host 'Creating zip'
$viewZip = $targetDirectory + "CalciumWinRTView_VS12_CS.zip"
Write-Host 'Outputting zip file to ' $viewZip
$zip.CreateZip($viewZip, $tempDirectory, $true, "")

if (Test-Path $tempDirectory)
{
    Write-Host 'Temp directory already exists. Removing it.'
    get-childitem $tempDirectory -recurse | remove-item -recurse -force
    Remove-Item -Recurse -Force $tempDirectory
}

$copyToVS = $false

if ($copyToVS)
{
    Write-Host 'Copying zip files to Visual Studio directories.'
    
    $vsPhoneProjectDir = 'C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\ProjectTemplates\CSharp\Windows Store\1033\'
    Copy-Item $appZip $vsPhoneProjectDir -force
    
    $vsPhoneItemDir = 'C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\ItemTemplates\CSharp\Windows Store\1033\'
    Copy-Item $viewZip $vsPhoneItemDir -force
}

Write-Host 'Complete'